package com.zjsru.plan2024.oneday;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: cookLee
 * @Date: 2024-01-21
 * 按分隔符拆分字符串
 */
public class SplitWordsBySeparator {

    /**
     * 主
     * \
     * 输入：words = ["one.two.three","four.five","six"], separator = "."
     * 输出：["one","two","three","four","five","six"]
     * 解释：在本示例中，我们进行下述拆分：
     * "one.two.three" 拆分为 "one", "two", "three"
     * "four.five" 拆分为 "four", "five"
     * "six" 拆分为 "six"
     * 因此，结果数组为 ["one","two","three","four","five","six"] 。
     * \
     * @param args args
     */
    public static void main(String[] args) {
        SplitWordsBySeparator splitWordsBySeparator = new SplitWordsBySeparator();
        List<String> words = Arrays.asList("one.two.three", "four.five", "six");
        char separator = '.';
        System.out.println(splitWordsBySeparator.splitWordsBySeparator(words, separator));
    }


    /**
     * 按分隔符拆分单词
     *
     * @param words     字词
     * @param separator 分离器
     * @return {@link List}<{@link String}>
     */
    public List<String> splitWordsBySeparator(List<String> words, char separator) {
        List<String> ans = new ArrayList<>();
        for (String word : words) {
            this.helper(word,ans,separator);
        }
        return ans.stream().filter(v -> !v.isEmpty()).collect(Collectors.toList());
    }

    /**
     * 帮手
     *
     * @param word 字
     * @param ans  ans
     */
    private void helper(String word, List<String> ans,char separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (c != separator) {
                sb.append(c);
            }
            if(c == separator || i == word.length() - 1){
                ans.add(sb.toString());
                sb.delete(0,sb.length());
            }
        }
    }

    /**
     * 按分隔符拆分单词2
     *
     * @param words     字词
     * @param separator 分离器
     * @return {@link List}<{@link String}>
     */
    public List<String> splitWordsBySeparator2(List<String> words, char separator) {
        List<String> ans = new ArrayList<>();
        for (String word : words) {
            for (int i = 0, j = 0; j <= word.length(); j++) {
                if (j != word.length() && word.charAt(j) != separator) {
                    continue;
                }
                if (j > i) {
                    ans.add(word.substring(i, j));
                }
                i = j + 1;
            }
        }
        return ans;
    }

}
